#include "..\include_eapi_header.h"
#include<gdiplus.h>
#include<shlwapi.h>
#pragma comment(lib, "gdiplus.lib")

namespace eapiGetImageSize {


	SIZE GetImageSize(const char* ImagePath) {
		SIZE ret = { -1,-1 };

		Gdiplus::GdiplusStartupInput gdiplusStartupInput;
		ULONG_PTR gdiplusToken;
		if (GdiplusStartup(&gdiplusToken, &gdiplusStartupInput, nullptr) != 0)
			return ret;

		if (!PathFileExistsA(ImagePath)) {
			Gdiplus::GdiplusShutdown(gdiplusToken);
			return ret;
		}

		int widesize = MultiByteToWideChar(CP_ACP, 0, ImagePath, -1, NULL, 0);
		wchar_t* wImagePath = new wchar_t[widesize];
		int convresult = MultiByteToWideChar(CP_ACP, 0, ImagePath, -1, wImagePath, widesize);
		Gdiplus::Bitmap* image = Gdiplus::Bitmap::FromFile(wImagePath);
		delete[] wImagePath;

		if (image->GetLastStatus() != Gdiplus::Ok) {
			Gdiplus::GdiplusShutdown(gdiplusToken);
			return ret;
		}

		ret.cx = image->GetWidth();
		ret.cy = image->GetHeight();

		Gdiplus::GdiplusShutdown(gdiplusToken);
		return ret;
	}

	SIZE GetImageSize(LPBYTE ImageData, size_t Length) {
		SIZE ret = { -1,-1 };
		Gdiplus::GdiplusStartupInput gdiplusStartupInput;
		ULONG_PTR gdiplusToken;
		Gdiplus::GdiplusStartup(&gdiplusToken, &gdiplusStartupInput, NULL);

		HGLOBAL hGlobal = GlobalAlloc(GMEM_FIXED, Length);
		if (!hGlobal) {
			Gdiplus::GdiplusShutdown(gdiplusToken);
			return ret;
		}
		memcpy(hGlobal, ImageData, Length);
		IStream* pStream = NULL;
		if (CreateStreamOnHGlobal(hGlobal, TRUE, &pStream) != S_OK) {
			Gdiplus::GdiplusShutdown(gdiplusToken);
			return ret;
		}
		Gdiplus::Bitmap* pBitmap = Gdiplus::Bitmap::FromStream(pStream);
		if (!pBitmap) {
			Gdiplus::GdiplusShutdown(gdiplusToken);
			return ret;
		}
		ret.cy = pBitmap->GetHeight();
		ret.cx = pBitmap->GetWidth();
		delete pBitmap;
		pStream->Release();

		Gdiplus::GdiplusShutdown(gdiplusToken);
		return ret;

	}
}

EAPI_EXTERN_C void eapi_GetImageWidth_31_eapi(PMDATA_INF pRetData, INT nArgCount, PMDATA_INF pArgInf)
{
	if (pArgInf->m_dtDataType == SDT_TEXT && pArgInf->m_pText && *pArgInf->m_pText != '\0') {

		pRetData->m_int = eapiGetImageSize::GetImageSize(pArgInf->m_pText).cx;
	}
	else if (pArgInf->m_dtDataType == SDT_BIN)
	{

		pRetData->m_int = eapiGetImageSize::GetImageSize(get_ebin_data(pArgInf->m_pBin), get_ebin_lenth(pArgInf->m_pBin)).cx;
	}
	else
	{
		pRetData->m_int = -1;
	}

}

